package com.csjbot.snowbotagingtest;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StatFs;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.android.core.util.SharedUtil;
import com.csjbot.csjbase.log.Csjlogger;
import com.csjbot.snowbot_rogue.camera.CameraInterface;
import com.csjbot.snowbot_rogue.utils.Constant;
import com.csjbot.snowbot_rogue.utils.WeakReferenceHandler;

import net.steamcrafted.loadtoast.LoadToast;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class VideoRecordFragment extends Fragment implements View.OnClickListener{

    private Camera mCamera;
    private SurfaceView mSurfaceView;
    private SurfaceHolder mSurfaceHolder;
    private Button startButton;
    private boolean mIsRecording = false;
    private MediaRecorder mediaRecorder;
    private LoadToast loadToast = null;
    private int recordTime = 0;
    private VideoRecordActivityHandler mHandler = new VideoRecordActivityHandler(this);
    private String currentFileName = "";
    private int autoTakePhotoCD = 5;
    private boolean isInAutoTakePhoto = false;

    public static VideoRecordFragment newInstance(){
        return new VideoRecordFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_video_record, container, false);
        init(view);
        return view;
    }

    private void init(View view){
        loadToast = new LoadToast(getActivity());
        loadToast.setText("录制中");

        final boolean autoTakePhoto = false;
        final boolean autoRecord = false;

        mSurfaceView = (SurfaceView) view.findViewById(R.id.surfaceview);
        mSurfaceHolder = mSurfaceView.getHolder();

        mSurfaceHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
//                releaseCamera();
            }

            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                initpreview();

                if (autoTakePhoto) {
                    autoTakePhoto();
                }

                if (autoRecord) {
                    loadToast.setText("准备录制111");
                    loadToast.show();

                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            startmediaRecorder();
                        }
                    }, 1000);
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

            }
        });

        startButton = (Button) view.findViewById(R.id.start);
        if (autoTakePhoto) {
            startButton.setVisibility(View.GONE);
        }
        startButton.setOnClickListener(this);

    }

    public void startAction(){
        if(mCameraOpenStatus == 10){
            ((TestActivity)getActivity()).sendLogMessage("摄像机打开成功",10);
        }else if(mCameraOpenStatus == 11){
            ((TestActivity)getActivity()).sendLogMessage("摄像机打开错误",11);
        }
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                action();
            }
        },1000);
    }
    public void stopAction(){
        handler.removeCallbacks(runnable);
    }

    Handler handler = new Handler();

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if(mIsRecording){
                stopmediaRecorder();

                action();
            }
        }
    };

    private void clearDir(){
        File file = new File("/mnt/sdcard/csjbot/video/");
        if(file.exists()){
            for (File f : file.listFiles() ){
                f.delete();
            }
        }
    }

    private void action(){
        if(getSDFreeSize() < 60){
            return;
        }
        startmediaRecorder();
        handler.postDelayed(runnable,(1000*60*30));
//        handler.postDelayed(runnable,(1000*30));
    }

    private void stopmediaRecorder() {
        if (mediaRecorder != null) {
            if (mIsRecording) {
                try {
                    //下面三个参数必须加，不加的话会奔溃，在mediarecorder.stop();
                    //报错为：RuntimeException:stop failed
                    mediaRecorder.setOnErrorListener(null);
                    mediaRecorder.setOnInfoListener(null);
                    mediaRecorder.setPreviewDisplay(null);
                    mediaRecorder.stop();

                    Toast.makeText(getActivity(), "结束录制", Toast.LENGTH_SHORT).show();
                    ((TestActivity)getActivity()).sendLogMessage("结束录像...");
                } catch (IllegalStateException e) {
                } catch (RuntimeException e) {
                }
                //mCamera.lock();
                mediaRecorder.reset();
                mediaRecorder.release();
                mediaRecorder = null;
                mIsRecording = false;

                if (mCamera != null) {
                    try {
                        mCamera.reconnect();
                    } catch (IOException e) {
                        Toast.makeText(getActivity(), "reconect fail", Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }
                }
                loadToast.success();
                recordTime = 0;
            }
        }
    }

    private void startmediaRecorder() {
        mCamera.unlock();

        if (mediaRecorder == null) {
            Csjlogger.debug("initVideoRecord");
            mIsRecording = true;

            CamcorderProfile mProfile = CamcorderProfile.get(CameraInterface.getInstance().getCameraId()
                    , CamcorderProfile.QUALITY_480P);

            //1st. Initial state
            mediaRecorder = new MediaRecorder();
            mediaRecorder.setCamera(mCamera);

            //2st. Initialized state

            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
            mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);

            //3st. config
            mediaRecorder.setOutputFormat(mProfile.fileFormat);
            mediaRecorder.setAudioEncoder(mProfile.audioCodec);
            mediaRecorder.setVideoEncoder(mProfile.videoCodec);
            mediaRecorder.setOutputFile(getName());
            mediaRecorder.setVideoSize(640, 480);
//            mediaRecorder.setVideoSize(mProfile.videoFrameWidth, mProfile.videoFrameHeight);
            mediaRecorder.setVideoFrameRate(mProfile.videoFrameRate);
            mediaRecorder.setVideoEncodingBitRate(mProfile.videoBitRate);
            mediaRecorder.setAudioEncodingBitRate(mProfile.audioBitRate);
            mediaRecorder.setAudioChannels(mProfile.audioChannels);
            mediaRecorder.setAudioSamplingRate(mProfile.audioSampleRate);

            mediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
        }
        try {
            mediaRecorder.prepare();
            mediaRecorder.start();
            Toast.makeText(getActivity(), "开始录制", Toast.LENGTH_SHORT).show();
            ((TestActivity)getActivity()).sendLogMessage("开始录像...");
//			mediaRecorder.set
        } catch (Exception e) {

            mIsRecording = false;
            Toast.makeText(getActivity(), "fail", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
            mCamera.lock();
        }
    }
    private String getName() {
        createFolder(ConstantsPath.testVideoResultPath);
        // 如 {SDCARD_PATH}/csjbot/video/1472475030.3pg
        currentFileName = ConstantsPath.testVideoResultPath +"/"+ ((TestActivity)getActivity()).stampToDate(String.valueOf(System.currentTimeMillis()));
        String fileName = currentFileName + ".3gp";
        return fileName;
    }



    public void createFolder(String folderPath) {
        File file = new File(folderPath);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    private class VideoRecordActivityHandler extends WeakReferenceHandler<VideoRecordFragment> {
        public VideoRecordActivityHandler(VideoRecordFragment reference) {
            super(reference);
        }

        @Override
        protected void handleMessage(VideoRecordFragment reference, Message msg) {

        }
    }

    private Runnable autoTakePhotoRunnable = new Runnable() {
        @Override
        public void run() {
            autoTakePhotoCD--;
            loadToast.setText(String.valueOf(autoTakePhotoCD));

            if (mCamera != null & autoTakePhotoCD == 0) {
                autoTakePhotoCD = 3;
                // TODO 这里加个声音
                mCamera.takePicture(null, null, null, new Camera.PictureCallback() {

                    /**
                     * Called when image data is available after a picture is taken.
                     * The format of the data depends on the context of the callback
                     * and {@link Camera.Parameters} settings.
                     *
                     * @param data   a byte array of the picture data
                     * @param camera the Camera service object
                     */
                    @Override
                    public void onPictureTaken(final byte[] data, Camera camera) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                                try {
                                    createFolder(Constant.SDCARD_VIDEO_PATH);
                                    saveFile(bitmap, Constant.SDCARD_VIDEO_PATH + System.currentTimeMillis() + ".jpg");
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }).start();
                    }
                });
                loadToast.success();

                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        isInAutoTakePhoto = false;
                        SharedUtil.setPreferInt("AIUISERVICESWITCH", 1);
                    }
                }, 1000);
            } else if (mCamera != null) {
                mHandler.postDelayed(this, 1000);
            } else {
                autoTakePhotoCD = 3;
                mHandler.removeCallbacks(autoTakePhotoRunnable);
            }
        }
    };

    private void autoTakePhoto() {
        if (mCamera != null) {
            SharedUtil.setPreferInt("AIUISERVICESWITCH", 0);
            isInAutoTakePhoto = true;
        }
    }
    private int mCameraOpenStatus = -1;

    protected void initpreview() {
        mCamera = CameraInterface.getInstance().getCameraDevice();

        if (mCamera != null) {
            mCameraOpenStatus = 10;
        } else {
            mCameraOpenStatus = 11;
            loadToast.setText("摄像机打开错误");
            loadToast.show();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    loadToast.error();
                }
            }, 1000);
        }
    }

    @Override
    public void onPause() {
        stopmediaRecorder();
        super.onPause();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.start:
                if (!mIsRecording) {
                    startmediaRecorder();
                } else {
                    stopmediaRecorder();
                }

                if (mIsRecording) {
                    startButton.setText("停止");
                } else {
                    startButton.setText("开始");
                }
                break;
            default:
                break;
        }
    }

    /**
     * 保存文件
     *
     * @param bm
     * @param fileName
     * @throws IOException
     */
    public void saveFile(Bitmap bm, String fileName) throws IOException {
        if (getSDFreeSize() > 10) {
            File myCaptureFile = new File(fileName);
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
            bm.compress(Bitmap.CompressFormat.JPEG, 20, bos);
            bos.flush();
            bos.close();
        } else {
            stopmediaRecorder();
        }
    }
    /**
     * SD卡剩余空间
     *
     * @return
     */
    public static long getSDFreeSize() {
        //取得SD卡文件路径
        File path = Environment.getExternalStorageDirectory();
        StatFs sf = new StatFs(path.getPath());
        //获取单个数据块的大小(Byte)
        long blockSize = sf.getBlockSize();
        //空闲的数据块的数量
        long freeBlocks = sf.getAvailableBlocks();
        //返回SD卡空闲大小
        //return freeBlocks * blockSize;  //单位Byte
        //return (freeBlocks * blockSize)/1024;   //单位KB
        return (freeBlocks * blockSize) / 1024 / 1024; //单位MB
    }




    private Runnable recordRunnable = new Runnable() {
        @Override
        public void run() {
            recordTime++;
            loadToast.setText(String.format(Locale.getDefault(), "%02d : %02d", recordTime / 60, recordTime % 60));
            mHandler.postDelayed(this, 1000);
        }
    };

    private void startRecordHandler() {
        mHandler.removeCallbacks(recordRunnable);
        mHandler.post(recordRunnable);
    }

}
